package com.hl.framework.auth.config;


import com.hl.framework.auth.filter.ResponseFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class MySecurityConfig {

    @Resource
    private SpringSecurityHandler securityHandler;

    @Resource
    private ResponseFilter responseFilter;

    @Resource
    private AccessDeniedHandler accessDeniedHandler;
    /**
     * 认证失败处理类 Bean
     */
    @Resource
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.csrf(AbstractHttpConfigurer::disable);// 跨域请求问题（CORS）
        http.addFilterBefore(responseFilter, WebAsyncManagerIntegrationFilter.class).exceptionHandling(configurer -> {
            configurer.authenticationEntryPoint(authenticationEntryPoint);
            configurer.accessDeniedHandler(accessDeniedHandler);

        });
        http.authorizeHttpRequests((auth) -> auth
                .requestMatchers("/v3/api-docs/**").permitAll()
                .requestMatchers("/webjars/**").permitAll()
                .requestMatchers("/swagger-ui").permitAll()
                .requestMatchers("/swagger-ui/**").permitAll()
                .requestMatchers("/druid/**").permitAll()
                .requestMatchers("/actuator/**").permitAll()
                .requestMatchers("/public/**").permitAll()
                .requestMatchers("/anon/**").permitAll()
                .anyRequest().authenticated());


        http.formLogin(request -> {
                    request.disable();

                    // 添加登录处理器
                    request.successHandler(securityHandler).failureHandler(securityHandler);
                }).logout(AbstractHttpConfigurer::disable)//禁用默认登出页面
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))//禁用session，前																												后端分离不需要
                .httpBasic(AbstractHttpConfigurer::disable);


        return http.build();
    }


}